package com.chuantou.yuba.ui;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.toolbox.NetworkImageView;
import com.chuantou.yuba.R;
import com.chuantou.yuba.db.util.AlbumHelper;
import com.chuantou.yuba.pojo.Album;
import com.chuantou.yuba.pojo.AlbumBucket;
import com.chuantou.yuba.ui.widget.AlbumItem;
import com.chuantou.yuba.util.BitmapBinder;
import com.chuantou.yuba.util.Constants;
import com.chuantou.yuba.util.ViewHolder;

public class AlbumActivity extends BaseActionBarActivity {
	private static final int DEFAULT_PIC_NUMBER = 9;
	private AlbumHelper mHelper;
	private List<AlbumBucket> mBuckets;
	private ListView mListView;
	private AlbumBucketAdapter mBucketAdapter;
	private GridView mGridView;
	private GridView mHeaderGridView;
	private AlbumGridAdapter mGridAdapter;
	private AlbumGridAdapter mHeaderAdapter;
	private LayoutInflater mInflater;
	private ArrayList<String> mSelectedPics = new ArrayList<String>();
	private int mMaxNumber = DEFAULT_PIC_NUMBER;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mHelper = new AlbumHelper(getApplicationContext());
		mInflater = LayoutInflater.from(getApplicationContext());
		mMaxNumber = getIntent().getIntExtra(Constants.EXTRA_SIZE, DEFAULT_PIC_NUMBER);
		setContentView(R.layout.album);
		setupViews();
		loadAllImages();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.menu_album, menu);
		MenuItem item = menu.findItem(R.id.menu_finish);
		String title = getString(R.string.album_option_menu_count, mSelectedPics.size(), mMaxNumber);
		item.setTitle(title);
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.menu_finish:
			Intent data = new Intent();
			data.putStringArrayListExtra(Constants.EXTRA_DATA, mSelectedPics);
			setResult(RESULT_OK, data);
			finish();
			return true;
		default:
			break;
		}
		return super.onOptionsItemSelected(item);
	}

	private void setupViews() {
		mListView = (ListView) findViewById(R.id.list);
		View headerView = mInflater.inflate(R.layout.album_header, null);
		mHeaderGridView = (GridView) headerView.findViewById(R.id.album_header);
		mHeaderAdapter = new AlbumGridAdapter(null);
		mHeaderGridView.setAdapter(mHeaderAdapter);
		mListView.addHeaderView(headerView);
		mListView.setAdapter(mBucketAdapter = new AlbumBucketAdapter());
		mListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				AlbumBucket bucket = (AlbumBucket) parent.getItemAtPosition(position);
				List<Album> albums = bucket.getImage();
				mGridView.setAdapter(mGridAdapter = new AlbumGridAdapter(albums));
				mGridAdapter.notifyDataSetChanged();
				mListView.setVisibility(View.GONE);
				mGridView.setVisibility(View.VISIBLE);
			}
		});
		mGridView = (GridView) findViewById(R.id.album_grid);
		mGridView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				Album album = (Album) parent.getItemAtPosition(position);
				String path = album.getPath();
				if (mSelectedPics.contains(path)) {
					mGridAdapter.notifyDataSetChanged();
					mSelectedPics.remove(path);
				} else {
					if (mSelectedPics.size() >= mMaxNumber) {
						Toast.makeText(getApplicationContext(), getString(R.string.pick_too_much_number, mMaxNumber), Toast.LENGTH_SHORT).show();
					} else {
						mSelectedPics.add(path);
						mGridAdapter.notifyDataSetChanged();
					}
				}
				supportInvalidateOptionsMenu();
			}
		});
		mHeaderGridView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				Album album = (Album) parent.getItemAtPosition(position);
				String path = album.getPath();
				if (mSelectedPics.contains(path)) {
					mHeaderAdapter.notifyDataSetChanged();
					mSelectedPics.remove(path);
				} else {
					if (mSelectedPics.size() >= mMaxNumber) {
						Toast.makeText(getApplicationContext(), getString(R.string.pick_too_much_number, mMaxNumber), Toast.LENGTH_SHORT).show();
					} else {
						mSelectedPics.add(path);
						mHeaderAdapter.notifyDataSetChanged();
					}
				}
				supportInvalidateOptionsMenu();
			}
		});
	}

	private void loadAllImages() {
		new AsyncTask<Void, Void, List<AlbumBucket>>() {
			private List<Album> mLatestAlbums;

			@Override
			protected List<AlbumBucket> doInBackground(Void... params) {
				List<AlbumBucket> all = mHelper.getAllBuckets();
				mLatestAlbums = mHelper.getLatestAlbums(8);
				return all;
			}

			protected void onPostExecute(List<AlbumBucket> result) {
				mHeaderAdapter.add(mLatestAlbums);
				mHeaderAdapter.notifyDataSetChanged();
				mBuckets = result;
				mBucketAdapter.notifyDataSetChanged();
			}

		}.execute();
	}

	class AlbumBucketAdapter extends BaseAdapter {
		@Override
		public int getCount() {
			return mBuckets == null ? 0 : mBuckets.size();
		}

		@Override
		public Object getItem(int position) {
			return mBuckets == null ? null : mBuckets.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			if (convertView == null) {
				convertView = mInflater.inflate(R.layout.album_bucket_item, null);
			}
			NetworkImageView imageView = ViewHolder.get(convertView, R.id.album_cover);
			AlbumBucket bucket = mBuckets.get(position);
			Album album = bucket.getImage().get(0);
			String originalPath = album.getPath();
			String path = getThumbnailPath(album.getId(), originalPath);
			String url = Uri.fromFile(new File(path)).toString();
			BitmapBinder.bindNetImage(getApplicationContext(), imageView, url, R.drawable.album_image_default, false);
			TextView nameView = ViewHolder.get(convertView, R.id.album_name);
			nameView.setText(String.format("%s(%d)", bucket.getName(), bucket.getCount()));
			return convertView;
		}
	}

	class AlbumGridAdapter extends BaseAdapter {
		private List<Album> mAlbums = null;

		public AlbumGridAdapter(List<Album> albums) {
			this.mAlbums = albums;
		}

		public void add(List<Album> albums) {
			if (mAlbums == null) {
				mAlbums = albums;
			} else {
				if (albums != null && !albums.isEmpty()) {
					mAlbums.addAll(albums);
				}
			}
		}

		@Override
		public int getCount() {
			return mAlbums == null ? 0 : mAlbums.size();
		}

		@Override
		public Object getItem(int position) {
			return mAlbums == null ? null : mAlbums.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			if (convertView == null) {
				convertView = mInflater.inflate(R.layout.album_grid_item, null);
			}
			AlbumItem itemView = ViewHolder.get(convertView, R.id.image);
			Album album = mAlbums.get(position);
			String originalPath = album.getPath();
			itemView.setChecked(mSelectedPics.contains(originalPath));
			String path = getThumbnailPath(album.getId(), originalPath);
			String url = Uri.fromFile(new File(path)).toString();
			BitmapBinder.bindNetImage(getApplicationContext(), itemView, url, R.drawable.album_image_default, false);
			return convertView;
		}
	}

	private String getThumbnailPath(long id, String originalPath) {
		String thumbnailPath = mHelper.getThumbnail(id);
		return TextUtils.isEmpty(thumbnailPath) ? originalPath : thumbnailPath;
	}

	@Override
	public void onBackPressed() {
		if (mListView.getVisibility() == View.GONE) {
			mGridView.setVisibility(View.GONE);
			mListView.setVisibility(View.VISIBLE);
		} else {
			super.onBackPressed();
		}
	}

	@Override
	protected void onDestroy() {
		mHelper.destroy();
		super.onDestroy();
	}

}
